package top.lyf1210.yuwenrpcspringbootstarter.bootstrap;

import com.yuwen.yuwenRPC.proxy.ServiceProxy;
import com.yuwen.yuwenRPC.proxy.ServiceProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import top.lyf1210.yuwenrpcspringbootstarter.annotation.RpcReference;

import java.lang.reflect.Field;

/**
 * @ClassNameRpc
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/6 下午3:14
 * @Version 1.0
 **/

/**
 * Rpc服务消费者启动
 */
public class RpcConsumerBootstrap implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        //1.遍历对象所有信息
        Field[] declaredFields = beanClass.getDeclaredFields();
        for (Field field : declaredFields) {
            RpcReference rpcReference = field.getAnnotation(RpcReference.class);
            if (rpcReference != null) {
                //为属性生成代理对象
                Class<?> interfaceClass = rpcReference.interfaceClass();
                if(interfaceClass == void.class){
                    interfaceClass = field.getType();
                }
                field.setAccessible(true);
                Object proxyObject = ServiceProxyFactory.getProxy(interfaceClass);
                try {
                    field.set(bean,proxyObject);
                    field.setAccessible(false);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("为字段注入代理对象失败",e);
                }
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
